package com.qf.common.interceptor;

import com.qf.common.annotation.NoLoginCheck;
import com.qf.common.exception.CustomerException;
import com.qf.common.utils.JwtUtils;
import com.qf.common.utils.UserUtils;
import io.jsonwebtoken.Claims;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截的是controller还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            return false;//当前拦截的不是动态资源不放行，还有别的资源
        }
        HandlerMethod handlerMethod=(HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        boolean b = method.isAnnotationPresent(NoLoginCheck.class);
        if (b) {
            return true;//直接放行，证明已经登陆了
        }
        String token = request.getHeader("Token");
        if (!StringUtils.hasLength(token)){
            throw new CustomerException(403,"请重新登录");
        }
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Integer uid = (Integer)claims.get("uid");
            UserUtils.setUid(uid);
        }catch (Exception e){
            throw new CustomerException(403,"请重新登录");
        }

        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
